package com.talent.jiwen;

import android.app.Dialog;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.talent.jiwen.base.BaseFragment;
import com.talent.jiwen.home.AddProblemActivity;
import com.talent.jiwen.home.TogetherListActivity;
import com.talent.jiwen.http.common.ActivityLifeCycleEvent;
import com.talent.jiwen.http.common.ApiFactory;
import com.talent.jiwen.http.common.HttpUtil;
import com.talent.jiwen.http.common.ProgressSubscriber;
import com.talent.jiwen.http.result.GroupInfoResult;
import com.talent.jiwen.http.result.HomePageResult;
import com.talent.jiwen.model.GradeInfo;
import com.talent.jiwen.my.AboutUsActivity;
import com.talent.jiwen.my.CouponActivity;
import com.talent.jiwen.my.CreditActivity;
import com.talent.jiwen.my.NotificationActivity;
import com.talent.jiwen.my.PayActivity;
import com.talent.jiwen.my.PayDepositActivity;
import com.talent.jiwen.ui.widgets.ChooseGradeDialog;
import com.talent.jiwen.ui.widgets.CircleWaveView;
import com.talent.jiwen.ui.widgets.RemindDialog;
import com.talent.jiwen.ui.widgets.WelFareDialog;
import com.talent.jiwen.ui.widgets.waveView.WaveView;
import com.talent.jiwen.util.Constant;
import com.talent.jiwen.util.ImageUtil;
import com.talent.jiwen.util.LogUtil;
import com.talent.jiwen.util.MaterialDialogUtil;
import com.talent.jiwen.util.MyToast;
import com.talent.jiwen.util.SPConstant;
import com.talent.jiwen.util.SPUtil;

import org.greenrobot.eventbus.Subscribe;

import java.text.DecimalFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import butterknife.BindView;
import butterknife.OnClick;
import rx.Observable;

public class HomeFragment extends BaseFragment {
    @BindView(R.id.notifyLayout)
    RelativeLayout notifyLayout;
    @BindView(R.id.gradeLayout)
    RelativeLayout gradeLayout;
    @BindView(R.id.gradeTv)
    TextView gradeTv;
    @BindView(R.id.advertIv)
    ImageView advertIv;
    @BindView(R.id.addQuestionLayout)
    ImageView addQuestionLayout;
    @BindView(R.id.inviteLayout)
    RelativeLayout inviteLayout;
    @BindView(R.id.inviteTimeTv)
    TextView inviteTimeTv;
    @BindView(R.id.inviteIv)
    ImageView inviteIv;
    @BindView(R.id.wave)
    CircleWaveView wave;
    @BindView(R.id.wave_view)
    WaveView wave_view;

    private long createTime;//拼班创建时间
    private Handler handler;
    private TimeRunnable timeRunnable;
    private Thread timeThread;//计时相关

    private String groupId;//提问群组ID
    private int couponCount;//优惠券数量
    private boolean hasOrderNow = false;//当前是否有正在进行中的订单

    public static final String REFRESH_HOME_INFO = "refresh.home.info";
    public static final String REFRESH_SELECT_GRADE= "refresh.select.grade";

    private static final int HANDLER_WHAT_TIME_COUNT = 1;
    private static final int HANDLER_WHAT_TIME_STOP = 2;

    @Override
    protected void initData() {

        registEventBus();

        int selectGrade = SPUtil.intOut(SPConstant.SELECT_GRADE);
        if (selectGrade == 0){
            gradeTv.setText("选择年级");
        }else{
            gradeTv.setText(Constant.gradeMap.get(selectGrade));
        }
        getHomePageInfo();

        wave.addWave();
        wave.start();

        wave_view.setProgress(80);

    }

    @Override
    protected int provideContentViewId() {
        return R.layout.fragment_home_new;
    }

    @Subscribe
    public void onEvent(String flag){
        if (flag.equals(REFRESH_HOME_INFO)){
            getHomePageInfo();
        }else if (flag.equals(REFRESH_SELECT_GRADE)){
            int selectGrade = SPUtil.intOut(SPConstant.SELECT_GRADE);
            if (selectGrade == 0){
                gradeTv.setText("选择年级");
            }else{
                gradeTv.setText(Constant.gradeMap.get(selectGrade));
            }
        }
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        unRegistEventBus();
    }

    @OnClick({ R.id.advertIv , R.id.notifyLayout, R.id.gradeLayout, R.id.addQuestionLayout})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.advertIv:

                break;
            case R.id.notifyLayout:
                intentActivity(NotificationActivity.class);
                break;
            case R.id.gradeLayout:
                ChooseGradeDialog  gradeDialog=new ChooseGradeDialog(getActivity() ,new ChooseGradeDialog.OnTagClickListener() {
                    @Override
                    public void onClick(Dialog dialog, GradeInfo gradeInfo) {
                        gradeTv.setText(gradeInfo.getGradeName());
                        //保存选中的年级ID
                        SPUtil.intIn(SPConstant.SELECT_GRADE , gradeInfo.getGradeId());
                    }
                } , true);

                gradeDialog.show();

                if(SPUtil.intOut(SPConstant.SELECT_GRADE) != 0){
                    gradeDialog.setTagSelect(SPUtil.intOut(SPConstant.SELECT_GRADE));
                }

                break;
            case R.id.addQuestionLayout:
                if (inviteLayout.getVisibility() == View.VISIBLE){
                    showToast("您当前有拼单课程进行中，请先处理");
                }else{
                    if(SPUtil.intOut(SPConstant.SELECT_GRADE) == 0){
                        showToast("请先选择年级");
                    }else{
                        createGroupInfo();
                    }
                }

                break;
        }
    }

    /**获取拼班课程
     *
     */
    private void getHomePageInfo(){
        Map<String, String> map = new HashMap<>();
        map.put("studentId" , SPUtil.stringOut(SPConstant.USER_ID));

        Observable observable = ApiFactory.getEducationApiSingleton().getHomePageInfo(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<HomePageResult>(getActivity()) {
            @Override
            protected void _onNext(final HomePageResult homePageResult) {
                //保存用户之前选择的年级
                int selectGrade = homePageResult.getGradeLevel();
                if (selectGrade == 0){
                    gradeTv.setText("选择年级");
                }else{
                    gradeTv.setText(Constant.gradeMap.get(selectGrade));
                }
                SPUtil.intIn(SPConstant.SELECT_GRADE , homePageResult.getGradeLevel());

                //信用弹窗
                int disCreditCount = SPUtil.intOut(SPConstant.CREADIT_COUNT);
                if (homePageResult.getDiscreditCount() < 4){
                    if (disCreditCount < homePageResult.getDiscreditCount()){
                        showCreditDialog(homePageResult.getDiscreditCount() , homePageResult.getStudentStatus());
                    }
                }else{
                    showCreditDialog(homePageResult.getDiscreditCount() , homePageResult.getStudentStatus());
                }

                //免单弹窗
                showFreedDialog(homePageResult.getFreeOrderCount());
                //未支付订单信息
                if (null != homePageResult.getUnpaidOrderInfo()){
                    MaterialDialogUtil.getCommonDialog(getActivity(), "提示", "您当前有未支付订单,是否立即去支付"
                            , "确定", "取消"
                            , new MaterialDialogUtil.OnDialogPoNeClickListener() {
                                @Override
                                public void onPositive() {
                                    PayActivity.startPayActivity(getActivity() , homePageResult.getUnpaidOrderInfo().getOrderId());
                                }

                                @Override
                                public void onNegative() {

                                }
                            }).show();
                }
                //拼单信息
                if(null != homePageResult.getOrderInfo()){
                    createTime = homePageResult.getOrderInfo().getCreateTime();

                    showInvitingCourse(homePageResult.getOrderInfo().getAnswerTime() , homePageResult.getOrderInfo().getGroupId()
                            , homePageResult.getOrderInfo().getOrderId());
                }else{
                    if(null != inviteLayout){
                        inviteLayout.setVisibility(View.GONE);
                    }
                }
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,false);
    }

    /**进入发起提问之前先创建群组
     *
     */
    private void createGroupInfo(){
        //创建群组前groupId先置为空
        groupId = "";

        Map<String, String> map = new HashMap<>();
        map.put("studentId" , SPUtil.stringOut(SPConstant.USER_ID));

        Observable observable = ApiFactory.getEducationApiSingleton().createGroupInfo(SPUtil.stringOut(SPConstant.TOKEN) , map);
        HttpUtil.getInstance().toSubscribe(observable, new ProgressSubscriber<GroupInfoResult>(getActivity()) {
            @Override
            protected void _onNext(GroupInfoResult groupInfoResult) {

                groupId = groupInfoResult.getGroupId();
                couponCount = groupInfoResult.getAvailableCouponCount();
                if (groupInfoResult.getExistImmediateStatus() == 0){
                    hasOrderNow = false;
                }else{
                    hasOrderNow = true;
                }

                AddProblemActivity.startAddProblemActivity(getActivity() , groupId , couponCount , hasOrderNow
                        , "","");
            }

            @Override
            protected void _onError(String message) {
                showToast(message);
            }
        }, ActivityLifeCycleEvent.DESTROY, lifecycleSubject,false);
    }

//    @Override
//    public void onActivityResult(int requestCode, int resultCode, Intent data) {
//        super.onActivityResult(requestCode, resultCode, data);
//        if (resultCode == Activity.RESULT_OK) {
//            switch (requestCode) {
//                case PictureConfig.CHOOSE_REQUEST:
//                    List<LocalMedia> pathList = new ArrayList<>();
//                    pathList.addAll(PictureSelector.obtainMultipleResult(data));
//
////                    AddProblemNewActivity.startAddProblemNewActivity(getActivity() , groupId , couponCount , hasOrderNow
////                            , "" ,JSON.toJSONString(pathList),"");
//
//                    break;
//            }
//        }
//    }

    /**显示免单次数
     *
     * @param freeCount
     */
    private void showFreedDialog(int freeCount){
        if (freeCount > 0){
            WelFareDialog welFareDialog = new WelFareDialog(getActivity());
            welFareDialog.setCancelable(false);
            if (!welFareDialog.isShowing()){
                welFareDialog.show();
            }

            welFareDialog.setContent(freeCount);
            welFareDialog.setOnUseClickListener(new WelFareDialog.OnUseClickListener() {
                @Override
                public void onUseClick() {
                    intentActivity(CouponActivity.class);
                }
            });
        }
    }
    /**显示失信dialog
     *
     * @param discreditCount
     */
    private void showCreditDialog(final int discreditCount , int studentStatus){
        SPUtil.intIn(SPConstant.CREADIT_COUNT , discreditCount);

        if (discreditCount < 3 && discreditCount > 0){
            //小于3次失提醒
            RemindDialog remindDialog = MaterialDialogUtil.getRemindDialog(getActivity(), R.mipmap.dialog_start_course, "你有" + discreditCount + "次失信记录"
                    , "取消", "查看", new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {

                        }
                    }, new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            intentActivity(CreditActivity.class);
                        }
                    });
            if(!remindDialog.isShowing()){
                remindDialog.show();
            }
        }else if (discreditCount == 3){
            //等于3次时判断是否需要缴费状态
            if (studentStatus == 3){
                //需要缴费状态，提示缴费
                RemindDialog dialog = MaterialDialogUtil.getRemindDialog(getActivity(), R.mipmap.dialog_start_course, "你已失信3次，需缴纳20元保证金才能继续正常使用"
                        , "取消", "去缴纳", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                intentActivity(PayDepositActivity.class);
                            }
                        });
                if (!dialog.isShowing()){
                    dialog.show();
                }
            }else{
                //其余查看
                RemindDialog remindDialog = MaterialDialogUtil.getRemindDialog(getActivity(), R.mipmap.dialog_start_course, "你有" + discreditCount + "次失信记录"
                        , "取消", "查看", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                intentActivity(CreditActivity.class);
                            }
                        });
                if (!remindDialog.isShowing()){
                    remindDialog.show();
                }
            }
        }else if (discreditCount > 3){
            //失信次数大于3次,判断学生状态
            if (studentStatus == 2){
                //失信状态，联系客服
                RemindDialog remindDialog = MaterialDialogUtil.getRemindDialog(getActivity(), R.mipmap.dialog_start_course, "您的失信次数已达上限,请联系客服专员解决"
                        , "取消", "去联系", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                intentActivity(AboutUsActivity.class);
                            }
                        });
                if (!remindDialog.isShowing()){
                    remindDialog.show();
                }
            }else{
                //显示查看，最多显示3次
                RemindDialog remindDialog = MaterialDialogUtil.getRemindDialog(getActivity(), R.mipmap.dialog_start_course, "你有" + 3 + "次失信记录"
                        , "取消", "查看", new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {

                            }
                        }, new View.OnClickListener() {
                            @Override
                            public void onClick(View view) {
                                intentActivity(CreditActivity.class);
                            }
                        });
                if(!remindDialog.isShowing()){
                    remindDialog.show();
                }
            }
        }
    }

    /**显示拼班课程
     *
     */
    private void showInvitingCourse(final long answerTime ,final String groupId , final String orderId){
        if(inviteLayout!=null){
            inviteLayout.setVisibility(View.VISIBLE);
        }

        inviteLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(answerTime < System.currentTimeMillis()){
                    MyToast.show(getActivity() ,"课程预约时间已过,已自动取消");
                    inviteLayout.setVisibility(View.GONE);
                }else{
                    TogetherListActivity.startTogetherActivity(getActivity() , answerTime +""  , createTime ,groupId ,orderId);
                }
            }
        });

        ImageUtil.loadCircleImage(getActivity() , SPUtil.getUserHeadImg() , inviteIv);

        handler = new Handler(){
            @Override
            public void handleMessage(Message msg) {
                if (msg.what == HANDLER_WHAT_TIME_COUNT){
                    String time =  (String)msg.obj;
                    if (inviteTimeTv != null){
                        inviteTimeTv.setText(time);
                    }
                }else{
                    if (inviteLayout != null){
                        LogUtil.e("首页拼班时间到，拼班结束");
                        inviteLayout.setVisibility(View.GONE);
                    }
                }

                super.handleMessage(msg);
            }
        };
        timeRunnable = new TimeRunnable();
        timeThread = new Thread(timeRunnable);

        timeThread.start();

    }

    class TimeRunnable implements  Runnable{
        boolean endThread;

        @Override
        public void run() {
            while (!endThread) {
                try {

                    Thread.sleep(1000);

                    int time = (int)((new Date().getTime() - createTime) / 1000);
                    String min = new DecimalFormat("00").format(time / 60);

                    String timeFormat;

                    String mm = new DecimalFormat("00").format(time / 60);
                    String ss = new DecimalFormat("00").format(time % 60);
                    timeFormat = new String( mm + ":" + ss);


                    Message msg = new Message();
                    msg.obj = timeFormat;

                    if (time > 15 * 60){
                        msg.what = HANDLER_WHAT_TIME_STOP;
                        endThread = true;
                    }else{
                        msg.what = HANDLER_WHAT_TIME_COUNT;
                    }

                    handler.sendMessage(msg);

                } catch (Exception e) {

                }
            }
        }
    }


}
